﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using VSD.OneStopService.BLL;

public partial class Modules_HoSoChoKyDuyet : System.Web.UI.Page
{
    List<ProfileStoreRepository.WFSProfileInfo> ListAllProf = new List<ProfileStoreRepository.WFSProfileInfo>();
    private ProfileStoreRepository resProfileStore = new ProfileStoreRepository();
    private ProfileHistoryRepository resHistory = new ProfileHistoryRepository();// Repository Lịch sử tiếp nhận, xử lý và trả hồ sơ
    private List<Department> AllDepartment;

    private bool IsDirector = false;
    private bool IsManager = false;
    private bool IsResolver = false;
    private bool CanSign = false;
    private bool CanViewAll = false;

    public int start = 0;
    int pageSize = 15;
    int pageSegSize = 1;
    int count = 0;

    protected void Page_Load(object sender, EventArgs e)
    {

        IsDirector = ContextUser.PermissionCollection.HasPermission(PermissionCode.LANHDAO_COQUAN);
        CanViewAll = ContextUser.PermissionCollection.HasPermission(PermissionCode.XEM_TOANBO_HOSO);
        IsManager = ContextUser.PermissionCollection.HasPermission(PermissionCode.LANHDAO_PHONG_CHUYENMON);
        IsResolver = ContextUser.PermissionCollection.HasPermission(PermissionCode.CHUYENVIEN_XULY);
        //--------------------------------------------------------
        bool AllowExecute = IsManager || IsResolver;
        CanSign = ContextUser.PermissionCollection.HasPermission(PermissionCode.KY_HOSO);

        if (!IsPostBack)
        {
            if (IsDirector || CanViewAll)
            {
                PnDrControl.Visible = true;
                BindDepartment();
            }
        }
    }

    public void Page_Prerender(object sender, EventArgs e)
    {
        bindProfiles();
    }

    public void bindProfiles()
    {
        try
        {
            if (IsDirector || CanViewAll) //Nếu là vai trò lãnh đạo CQ
            {
                int deptid = 0;
                if (CbDepartment.SelectedIndex > 0)
                    deptid = int.Parse(CbDepartment.SelectedValue.ToString());

                ListAllProf = resProfileStore.GetWaitForSignedProfiles(deptid, string.Empty, string.Empty, start, pageSize, out count).ToList();

                if (CkShowOwnerOnly.Checked)
                    ListAllProf.RemoveAll(r => r.SignerUserName != ContextUser.UserName);

                ListAllProf = ListAllProf.FindAll(r => r.SignerUserName == ContextUser.UserName);
                //ListAllProf.RemoveAll(r => r.SignerUserName == ContextUser.UserName);
            }
            else if (IsManager || (ContextUser.GlobalOption.EnabledViewAll.HasValue && ContextUser.GlobalOption.EnabledViewAll.Value)) //Nếu là vai trò phong
            {
                if (ContextUser.CurrentUser.DepartmentID.HasValue)
                    ListAllProf = resProfileStore.GetWaitForSignedProfiles(ContextUser.CurrentUser.DepartmentID.Value, string.Empty, string.Empty, start, pageSize, out count).ToList();
                //ListAllProf.AddRange(resProfileStore.GetWaitForSignedProfiles(0, ContextUser.UserName, null));
                ListAllProf = ListAllProf.Distinct(new DistinctProfile()).ToList();
            }
            else
            {
                ListAllProf = resProfileStore.GetWaitForSignedProfiles(0, string.Empty, ContextUser.UserName, start, pageSize, out count).ToList();
                //ListAllProf.AddRange(resProfileStore.GetWaitForSignedProfiles(0, ContextUser.UserName, null));
                ListAllProf = ListAllProf.Distinct(new DistinctProfile()).ToList();
            }
            rptProfiles.DataSource = ListAllProf;
            rptProfiles.DataBind();
        }
        catch (Exception)
        {

        }

        AspNetPager1.RecordCount = count;
        AspNetPager1.PageSize = pageSize;
        // AspNetPager1.CurrentPageIndex = 1;

        //if (AspNetPager1.PageCount <= 1) divPagination.Visible = false;
    }

    public void BindDepartment()
    {
        DepartmentRepository DeptRepos = new DepartmentRepository();
        AllDepartment = DeptRepos.GetAll().OrderBy(r => r.Name).ToList();
        AllDepartment.Insert(0, new Department() { Name = "Danh sách phòng ban", ID = 0 });
        CbDepartment.DataSource = AllDepartment;
        CbDepartment.DataTextField = "Name";
        CbDepartment.DataValueField = "ID";
        CbDepartment.DataBind();
    }

    protected void rptProfiles_ItemCommand(object source, RepeaterCommandEventArgs e)
    {
        if (IsDirector)
        {
            ProfileStore signingProfile = resProfileStore.Get(int.Parse(e.CommandArgument.ToString()));

            if (signingProfile.SignedUserName == ContextUser.CurrentUser.UserName)
            {
                //========================
                signingProfile.SignedUserName = ContextUser.CurrentUser.UserName;
                signingProfile.SignedName = ContextUser.CurrentUser.Name;
                signingProfile.Status = (byte)ServiceStatusCode.CodeValue.da_ky;
                signingProfile.SignedDate = DateTime.Now;
                signingProfile.Result = true;
            }

            //==========Ghi log xử lý hồ sơ=================
            ProfileHistory executeHistory = new ProfileHistory()
            {
                ProfileID = signingProfile.ID,
                StatusID = signingProfile.Status,
                StatusName = ServiceStatusCode.CodeName(signingProfile.Status),
                ActionName = "Lãnh đạo đã ký hồ sơ",
                ActionBy = ContextUser.CurrentUser.UserName,
                ProcessBy = ContextUser.CurrentUser.UserName,
                ActionDate = DateTime.Now,
                Consumer = signingProfile.SubscriberName,
                Conclusion = signingProfile.Conclusion
            };
            resHistory.Add(executeHistory);
            resHistory.SubmitChanges();

            resProfileStore.SubmitChanges();
            bindProfiles();
        }

        var script = "alert('Không được xử lý hồ sơ thay lãnh đạo');";
        ClientScript.RegisterClientScriptBlock(this.GetType(), "sample", script.ToString(), true);

        //lbMessage.Text = "không được xử lý hồ sơ thay lảnh đạo!";

    }

    protected void AspNetPager1_PageChanged(object sender, EventArgs e)
    {
        start = AspNetPager1.StartRecordIndex - 1;
        try
        {
            if (IsDirector || CanViewAll) //Nếu là vai trò lãnh đạo CQ
            {
                int deptid = 0;
                if (CbDepartment.SelectedIndex > 0)
                    deptid = int.Parse(CbDepartment.SelectedValue.ToString());

                ListAllProf = resProfileStore.GetWaitForSignedProfiles(deptid, string.Empty, string.Empty, start, pageSize, out count).ToList();

                if (CkShowOwnerOnly.Checked)
                    ListAllProf.RemoveAll(r => r.SignerUserName != ContextUser.UserName);

                ListAllProf = ListAllProf.FindAll(r => r.SignerUserName == ContextUser.UserName);
                //ListAllProf.RemoveAll(r => r.SignerUserName == ContextUser.UserName);
            }
            else if (IsManager || (ContextUser.GlobalOption.EnabledViewAll.HasValue && ContextUser.GlobalOption.EnabledViewAll.Value)) //Nếu là vai trò phong
            {
                if (ContextUser.CurrentUser.DepartmentID.HasValue)
                    ListAllProf = resProfileStore.GetWaitForSignedProfiles(ContextUser.CurrentUser.DepartmentID.Value, string.Empty, string.Empty, start, pageSize, out count).ToList();
                ListAllProf.AddRange(resProfileStore.GetWaitForSignedProfiles(0, ContextUser.UserName, null, start, pageSize, out count));
                ListAllProf = ListAllProf.Distinct(new DistinctProfile()).ToList();
            }
            else
            {
                ListAllProf = resProfileStore.GetWaitForSignedProfiles(0, string.Empty, ContextUser.UserName, start, pageSize, out count).ToList();
                ListAllProf.AddRange(resProfileStore.GetWaitForSignedProfiles(0, ContextUser.UserName, null, start, pageSize, out count));
                ListAllProf = ListAllProf.Distinct(new DistinctProfile()).ToList();
            }
            rptProfiles.DataSource = ListAllProf;
            rptProfiles.DataBind();
        }
        catch (Exception)
        {

            throw;
        }
    }

    class DistinctProfile : IEqualityComparer<ProfileStoreRepository.WFSProfileInfo>
    {
        public bool Equals(ProfileStoreRepository.WFSProfileInfo x, ProfileStoreRepository.WFSProfileInfo y)
        {
            return x.ProfileCode.Equals(y.ProfileCode);
        }

        public int GetHashCode(ProfileStoreRepository.WFSProfileInfo obj)
        {
            return obj.ProfileCode.GetHashCode(); ;
        }
    }


}